package com.conan.zone.rss.support.parser;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.xerces.parsers.SAXParser;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;

import com.conan.zone.rss.model.RssItem;
import com.conan.zone.util.CommonUtil;

/**
 * 
 * @author Conan
 *
 */
public abstract class AbstractParser extends DefaultHandler implements IRssParser {
	
	protected List<RssItem> list;
	protected boolean startItem = false;
	protected RssItem item = null;
	protected Map<Integer,Integer> importedValueTags =null;
	protected final static int VALUE_INIT = 0;
	protected final static int VALUE_STARTED = 1;
	protected final static int VALUE_IMPORTED = 2;
	
	{
		resetInit();
	}
	
	@Override
	public List<RssItem> parser(String url) {
		try{
			logger.info("开始分析URL:"+url);
			list = new ArrayList<RssItem>();
			
			SAXParser parser = new SAXParser();
			parser.setContentHandler(this);
			parser.parse(new InputSource(new URL(url).openStream()));
			
//			for (RssItem item : list) {
//				System.out.println("Title:"+item.getTitle());
//			}
			
			return list;
		}catch(Exception e){
			e.printStackTrace();
			logger.error(CommonUtil.printErrorTrace(e));
		}
		return new ArrayList<RssItem>();
	}
	
	/**
	 * reset一些初始化信息
	 */
	protected void resetInit(){
		//System.setOut(new PrintStream(new FileOutputStream(new File("d:\\xml.txt"))));
		startItem = false;
		item = null;
		importedValueTags = new HashMap<Integer,Integer>();
		for(int i=0;i<7;i++){
			importedValueTags.put(i, VALUE_INIT);
		}
	}

}
